import axios from 'axios'
import { Message } from 'element-ui'
import { getToken, toLogin } from './ssoUtils'
import config from './ssoConfig'
import api from './api'

// sso环境信息
const ssoEnv =
  process.env.NODE_ENV === 'development' ? config.sso.dev : config.sso.pro

// const baseURL = 'http://localhost:8090/sso'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: api.baseApi,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers[ssoEnv.REQUEST_HEADER_TOKEN_KEY] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.status === 401) {
      toLogin()
    } else if (res.status < 200 || res.status > 300) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error)
    Message({
      message: error.response.data.msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
